<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="jquery,ajax,json,jsonp," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="js中ajax的基本步骤1234567891011121314151617window.onload = function () &amp;#123;        var xhr = new XMLHttpRequest();        xhr.open(&apos;post&apos;,&apos;XXX.php&apos;);        xhr.setRequestHeader(&apos;Content-Type&apos;,&apos;applicatio">
<meta name="keywords" content="jquery,ajax,json,jsonp">
<meta property="og:type" content="article">
<meta property="og:title" content="JQuery中ajax同源和跨域请求原理及封装">
<meta property="og:url" content="http://yoursite.com/2017/03/25/JQuery中ajax同源和跨域请求原理及封装/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="js中ajax的基本步骤1234567891011121314151617window.onload = function () &amp;#123;        var xhr = new XMLHttpRequest();        xhr.open(&apos;post&apos;,&apos;XXX.php&apos;);        xhr.setRequestHeader(&apos;Content-Type&apos;,&apos;applicatio">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-09-18T12:02:14.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JQuery中ajax同源和跨域请求原理及封装">
<meta name="twitter:description" content="js中ajax的基本步骤1234567891011121314151617window.onload = function () &amp;#123;        var xhr = new XMLHttpRequest();        xhr.open(&apos;post&apos;,&apos;XXX.php&apos;);        xhr.setRequestHeader(&apos;Content-Type&apos;,&apos;applicatio">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/03/25/JQuery中ajax同源和跨域请求原理及封装/"/>





  <title>JQuery中ajax同源和跨域请求原理及封装 | Hexo</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Hexo</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/03/25/JQuery中ajax同源和跨域请求原理及封装/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="shine-wl">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://dynamic-image.yesky.com/300x-/uploadImages/upload/20140912/upload/201409/wylnwjynkxijpg.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hexo">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JQuery中ajax同源和跨域请求原理及封装</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-25T10:44:37+08:00">
                2017-03-25
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="js中ajax的基本步骤"><a href="#js中ajax的基本步骤" class="headerlink" title="js中ajax的基本步骤"></a>js中ajax的基本步骤</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">window</span>.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">        <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</div><div class="line">        xhr.open(<span class="string">'post'</span>,<span class="string">'XXX.php'</span>);</div><div class="line">        xhr.setRequestHeader(<span class="string">'Content-Type'</span>,<span class="string">'application/x-www-form-urlencoded'</span>);</div><div class="line">        xhr.send(<span class="literal">null</span>);</div><div class="line">        xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">            <span class="keyword">if</span>(xhr.readyState == <span class="number">4</span>)&#123;</div><div class="line">                <span class="keyword">if</span>(xhr.status == <span class="number">200</span>)&#123;</div><div class="line">                    <span class="comment">/*返回json数据*/</span></div><div class="line">                    <span class="built_in">console</span>.log(xhr.responseText);</div><div class="line">                    <span class="comment">/*转换json对象*/</span></div><div class="line">                    <span class="keyword">var</span> data = <span class="built_in">JSON</span>.parse(xhr.responseText);</div><div class="line">                    <span class="built_in">console</span>.log(data);</div><div class="line">                &#125;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<a id="more"></a>
<h1 id="同源和跨域"><a href="#同源和跨域" class="headerlink" title="同源和跨域"></a>同源和跨域</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">同源是指，域名，协议，端口均相同</div><div class="line">跨域，指的是浏览器不能执行其他网站的脚本。</div><div class="line">它是由浏览器的同源策略造成的，是浏览器对javascript施加的安全限制。</div></pre></td></tr></table></figure>
<h1 id="jQuery中ajax的使用"><a href="#jQuery中ajax的使用" class="headerlink" title="jQuery中ajax的使用"></a>jQuery中ajax的使用</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line">$(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">       $.ajax(&#123;</div><div class="line">           type:<span class="string">'post'</span>,</div><div class="line">           url:<span class="string">'地址'</span>,</div><div class="line">           data:&#123;<span class="attr">name</span>:<span class="string">'zbw'</span>&#125;, <span class="comment">// 根据接口文档来确定要传入的data数据 </span></div><div class="line">           <span class="keyword">async</span>:<span class="literal">true</span>,<span class="comment">//是否异步</span></div><div class="line">           success:<span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</div><div class="line">               <span class="built_in">console</span>.log(<span class="string">'success'</span>);</div><div class="line">               <span class="built_in">console</span>.log(data);</div><div class="line">           &#125;,</div><div class="line">           error:<span class="function"><span class="keyword">function</span> (<span class="params">info</span>) </span>&#123;</div><div class="line">               <span class="built_in">console</span>.log(<span class="string">'error'</span>);</div><div class="line">               <span class="built_in">console</span>.log(info);</div><div class="line">           &#125;,</div><div class="line">           <span class="comment">/*jquery ajax 常见参数*/</span></div><div class="line">           <span class="comment">/*dataType  强制转化成某种数据格式*/</span></div><div class="line">           <span class="comment">/*转换失败的时候  调用失败回调函数*/</span></div><div class="line">           dataType:<span class="string">'json'</span>,</div><div class="line">           <span class="comment">/*timeout  在通讯时间超出设定的时间时候中断ajax通讯*/</span></div><div class="line">           timeout:<span class="number">4000</span>,</div><div class="line">           <span class="comment">/*beforeSend 发送之前的回调函数  发送之前的业务*/</span></div><div class="line">           beforeSend:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">               <span class="keyword">var</span> $key = $(<span class="string">'#key'</span>);</div><div class="line">               <span class="keyword">if</span>(!$key.val())&#123;</div><div class="line">                   <span class="comment">/*beforeSend 返回的是false 终止发送*/</span></div><div class="line">                   <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">               &#125;</div><div class="line">           &#125;,</div><div class="line">           <span class="comment">/*complete 通讯完成回调函数  在成功或失败之后执行*/</span></div><div class="line">           complete:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">               <span class="built_in">console</span>.log(<span class="string">'complete'</span>);</div><div class="line">           &#125;</div><div class="line">       &#125;);</div><div class="line">   &#125;);</div></pre></td></tr></table></figure>
<h1 id="jQuery中ajax同源请求的封装"><a href="#jQuery中ajax同源请求的封装" class="headerlink" title="jQuery中ajax同源请求的封装"></a>jQuery中ajax同源请求的封装</h1><p>封装目的：降低代码的冗余,方便调用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">使用文档：</div><div class="line">参数名称          参数类型          参数默认值        参数说明</div><div class="line">type             string            get              请求的方式</div><div class="line">url              string            当前地址          请求的地址</div><div class="line"><span class="keyword">async</span>            boolean           <span class="literal">true</span>             是否的异步的方式 <span class="literal">false</span></div><div class="line">data             object            &#123;&#125;               需要发送的数据｛name:xgg｝</div><div class="line">success          <span class="function"><span class="keyword">function</span>                           成功回调函数</span></div><div class="line"><span class="function"><span class="title">error</span>            <span class="title">function</span>                           失败回调函数</span></div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/*申明一个全局变量*/</span></div><div class="line"><span class="built_in">window</span>.$ = &#123;&#125;;</div><div class="line"><span class="comment">/*在$对象里头申明一个属性指向一个叫ajax的函数*/</span></div><div class="line">$.ajax = <span class="function"><span class="keyword">function</span> (<span class="params">options</span>) </span>&#123;</div><div class="line">    <span class="comment">/*实现代码*/</span></div><div class="line">    <span class="comment">/*options对象传参*/</span></div><div class="line">    <span class="keyword">if</span>(!options || <span class="keyword">typeof</span> options != <span class="string">'object'</span>) <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line"></div><div class="line">    <span class="comment">/*设置默认参数*/</span></div><div class="line">    <span class="keyword">var</span> type = options.type !== <span class="string">'post'</span> ? <span class="string">'get'</span> : <span class="string">'post'</span>;</div><div class="line">    <span class="keyword">var</span> url = options.url || location.pathname;</div><div class="line">    <span class="keyword">var</span> <span class="keyword">async</span> = options.async !== <span class="literal">false</span> ? <span class="literal">true</span> : <span class="literal">false</span>;</div><div class="line">    <span class="keyword">var</span> data = <span class="keyword">typeof</span> options.data == <span class="string">'object'</span> ? options.data : &#123;&#125;;</div><div class="line"></div><div class="line">    <span class="comment">/*发送的数据需要  键值对的字符串格式  转换一下</span></div><div class="line"><span class="comment">    &#123;key:value,a:b&#125;-----&gt;key=value&amp;a=b*/</span></div><div class="line">    <span class="keyword">var</span> dataString = <span class="string">''</span>;</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> data)&#123;</div><div class="line">        dataString += key+<span class="string">'='</span>+data[key]+<span class="string">'&amp;'</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">/*if(dataString)&#123;</span></div><div class="line"><span class="comment">        dataString = dataString.slice(0,-1);</span></div><div class="line"><span class="comment">    &#125;*/</span></div><div class="line">    dataString = dataString &amp;&amp; dataString.slice(<span class="number">0</span>,<span class="number">-1</span>);</div><div class="line"></div><div class="line">    <span class="comment">/*ajax编程 基本步骤*/</span></div><div class="line">    <span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest();</div><div class="line">    <span class="comment">/*请求*/</span></div><div class="line">    xhr.open(type,type==<span class="string">'get'</span>?url+<span class="string">'?'</span>+dataString:url,<span class="keyword">async</span>);</div><div class="line">    <span class="keyword">if</span>(type!=<span class="string">'get'</span>)&#123;</div><div class="line">        xhr.setRequestHeader(<span class="string">'Content-Type'</span>,<span class="string">'application/x-www-form-urlencoded'</span>);</div><div class="line">    &#125;</div><div class="line">    xhr.send(type==<span class="string">'get'</span>?<span class="literal">null</span>:dataString);</div><div class="line">    <span class="comment">/*响应*/</span></div><div class="line">    xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">        <span class="comment">/*if(xhr.readyState == 4 &amp;&amp; xhr.status == 200)&#123;&#125;*/</span></div><div class="line">        <span class="keyword">if</span>(xhr.readyState == <span class="number">4</span>)&#123;</div><div class="line">            <span class="comment">/*通讯完成*/</span></div><div class="line">            <span class="keyword">if</span>(xhr.status == <span class="number">200</span>)&#123;</div><div class="line">                <span class="comment">/*成功*/</span></div><div class="line">                <span class="comment">/*获取数据*/</span></div><div class="line">                <span class="comment">/*需要和后台的数据格式对应*/</span></div><div class="line">                <span class="comment">/*前后端开发的约定：Content-Type 内容的类型*/</span></div><div class="line">                <span class="comment">/*Content-Type 如果包含xml返回的就xml*/</span></div><div class="line">                <span class="comment">/*Content-Type 如果包含json返回的就json*/</span></div><div class="line">                <span class="keyword">var</span> ct = xhr.getResponseHeader(<span class="string">'Content-Type'</span>);</div><div class="line">                <span class="comment">/*接收数据*/</span></div><div class="line">                <span class="keyword">var</span> result = <span class="literal">null</span>;</div><div class="line">                <span class="keyword">if</span>(ct.indexOf(<span class="string">'xml'</span>) &gt; <span class="number">-1</span>)&#123;</div><div class="line">                    result = xhr.responseXML; <span class="comment">// 获得 XML 形式的响应数据。</span></div><div class="line">                &#125;<span class="keyword">else</span> <span class="keyword">if</span>(ct.indexOf(<span class="string">'json'</span>) &gt; <span class="number">-1</span>)&#123;</div><div class="line">                    <span class="keyword">var</span> jsonString = xhr.responseText; <span class="comment">// 获得字符串形式的响应数据。</span></div><div class="line">                    result = jsonString &amp;&amp; <span class="built_in">JSON</span>.parse(jsonString);</div><div class="line">                &#125;<span class="keyword">else</span>&#123;</div><div class="line">                    result = xhr.responseText;</div><div class="line">                &#125;</div><div class="line">                <span class="comment">/*给成功的业务用*/</span></div><div class="line">                <span class="comment">/*调用成功回调函数*/</span></div><div class="line">                options.success &amp;&amp; options.success(result);</div><div class="line">            &#125;<span class="keyword">else</span>&#123;</div><div class="line">                <span class="comment">/*失败*/</span></div><div class="line">                <span class="keyword">var</span> info = &#123;<span class="attr">status</span>:xhr.status,<span class="attr">statusText</span>:xhr.statusText&#125;;</div><div class="line">                options.error &amp;&amp; options.error(info);</div><div class="line">            &#125;</div><div class="line"></div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h1 id="ajax中的跨域请求解决方法"><a href="#ajax中的跨域请求解决方法" class="headerlink" title="ajax中的跨域请求解决方法"></a>ajax中的跨域请求解决方法</h1><p>在Apache中配置反向代理（解决跨域问题）</p>
<p>通过产生一个script标签来实现跨域。因为script标签的src属性是没有跨域的限制的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 跨域只有get请求</span></div><div class="line"><span class="comment">// async属性指是否异步 </span></div><div class="line"><span class="comment">// 跨域的网站 http://doc.studyit.com/data.php</span></div><div class="line">&lt;script <span class="keyword">async</span> type=<span class="string">"text/javascript"</span> src=<span class="string">"http://doc.studyit.com/data.php?flag=1"</span>&gt;<span class="xml"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span></div></pre></td></tr></table></figure>
<p>比较方便的做法就是动态创建script标签，然后通过标签的src属性发送跨域请求，并且可以携带参数,后台响应的内容是js代码或函数调用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> script = <span class="built_in">document</span>.createElement(<span class="string">'script'</span>);</div><div class="line"><span class="keyword">var</span> param = <span class="string">'?flag=123&amp;callback=zbw'</span>;</div><div class="line">script.src = <span class="string">'http://doc.studyit.com/data.php'</span> + param;</div><div class="line"><span class="keyword">var</span> head = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'head'</span>)[<span class="number">0</span>];</div><div class="line">head.appendChild(script);</div></pre></td></tr></table></figure>
<h2 id="后台的data-php代码示例"><a href="#后台的data-php代码示例" class="headerlink" title="后台的data.php代码示例"></a>后台的data.php代码示例</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 是放在跨域域名的虚拟主机里的,这样才能形成跨域请求</span></div><div class="line"><span class="comment">// 通过get传入数据,在data.php中返回一个回调函数执行代码</span></div><div class="line"><span class="meta">&lt;?php</span> </div><div class="line">  $flag = $_GET[<span class="string">'flag'</span>]; <span class="comment">//获取url地址中的数据</span></div><div class="line">  $cbName = $_GET[<span class="string">'abc'</span>];<span class="comment">// callback名字后台一般是写死的,这里的名字为abc</span></div><div class="line">  <span class="comment">// echo 'var n=123;console.log(n);';</span></div><div class="line">  $arr = <span class="keyword">array</span>(<span class="string">'username'</span>=&gt;<span class="string">'lisi'</span>,<span class="string">'age'</span>=&gt;<span class="string">'12'</span>,<span class="string">'flag'</span>=&gt;$flag);</div><div class="line">  $str = json_encode($arr); <span class="comment">// 把数组转化为对象</span></div><div class="line">  <span class="comment">// 函数传入$str然后调用,函数$cbName是通过前端get传输的</span></div><div class="line">  <span class="keyword">echo</span> $cbName.<span class="string">'('</span>.$str.<span class="string">');'</span>;<span class="comment">// 函数调用</span></div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h1 id="jQuery中解决跨域的方法"><a href="#jQuery中解决跨域的方法" class="headerlink" title="jQuery中解决跨域的方法"></a>jQuery中解决跨域的方法</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">$.ajax(&#123;</div><div class="line">    url: <span class="string">'http://doc.studyit.com/data.php'</span>,</div><div class="line">    jsonp: <span class="string">'abc'</span>, <span class="comment">// 该属性的作用就是定制回调函数的key（等号左边的部分）</span></div><div class="line">    jsonpCallback: <span class="string">'helloworld'</span>, <span class="comment">// 该属性的作用就是定制回调函数的value（等号后面的部分）</span></div><div class="line">    dataType: <span class="string">'jsonp'</span>,</div><div class="line">  	<span class="comment">//其实设置了dataType: 'jsonp'后，$.ajax方法就和ajax XmlHttpRequest没什么关系了</span></div><div class="line">  	<span class="comment">//取而代之的则是JSONP协议。JSONP是一个非官方的协议</span></div><div class="line">  	<span class="comment">//它允许在服务器端集成Script tags返回至客户端，通过javascript callback的形式实现跨域访问。</span></div><div class="line">    data: &#123;</div><div class="line">        flag: <span class="number">123</span></div><div class="line">    &#125;,</div><div class="line">    success: <span class="function"><span class="keyword">function</span>(<span class="params">data</span>) </span>&#123;</div><div class="line">        <span class="built_in">console</span>.log(data);</div><div class="line">    &#125;</div><div class="line">&#125;);</div><div class="line"><span class="comment">// 更改回调函数的名字的地址为: http://doc.studyit.com/data.php?abc=helloworld&amp;flag=123&amp;_=1505731847487</span></div><div class="line"><span class="comment">// 没有更改回调函数的名字的地址为:	http://doc.studyit.com/data.php?callback=jQuery1112025613064331916147_1505555830752&amp;flag=123&amp;_=1505555830753</span></div></pre></td></tr></table></figure>
<h1 id="jQuery中ajax的跨域请求封装函数"><a href="#jQuery中ajax的跨域请求封装函数" class="headerlink" title="jQuery中ajax的跨域请求封装函数"></a>jQuery中ajax的跨域请求封装函数</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">obj</span>) </span>&#123;</div><div class="line">           <span class="comment">// 默认参数</span></div><div class="line">           <span class="keyword">var</span> defaults = &#123;</div><div class="line">               jsonp: <span class="string">'callback'</span></div><div class="line">           &#125;;</div><div class="line">           <span class="comment">// 传入的对象覆盖默认参数</span></div><div class="line">           <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> obj) &#123;</div><div class="line">               defaults[key] = obj[key];</div><div class="line">           &#125;;</div><div class="line"></div><div class="line">           <span class="comment">// 默认回调函数名称</span></div><div class="line">           <span class="comment">// replace(/\D/g, '') 把非数字替换成空字符串</span></div><div class="line">           <span class="keyword">var</span> cbName = <span class="string">'jQuery'</span> + (<span class="string">'v1.11.1'</span> + <span class="built_in">Math</span>.random()).replace(<span class="regexp">/\D/g</span>, <span class="string">''</span>) + <span class="string">'_'</span> + <span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</div><div class="line">           <span class="comment">// 替换默认的回调函数名称</span></div><div class="line">           <span class="keyword">if</span> (defaults.jsonpCallback) &#123;</div><div class="line">               cbName = defaults.jsonpCallback;</div><div class="line">           &#125;;</div><div class="line"></div><div class="line">           <span class="comment">// 定义回调函数然后再后台调用  echo $cbName.'('.$str.');';</span></div><div class="line">           <span class="comment">// data就是data.php中的$str</span></div><div class="line">           <span class="comment">// 在把data传入到封装的ajax跨域函数传入的对象中的success函数中</span></div><div class="line">           <span class="built_in">window</span>[cbName] = <span class="function"><span class="keyword">function</span>(<span class="params">data</span>) </span>&#123;</div><div class="line">               defaults.success(data); <span class="comment">// 执行success函数</span></div><div class="line">           &#125;;</div><div class="line"></div><div class="line">           <span class="comment">// 发送跨域请求</span></div><div class="line">           <span class="keyword">var</span> script = <span class="built_in">document</span>.createElement(<span class="string">'script'</span>);</div><div class="line">           <span class="keyword">var</span> param = <span class="string">''</span>;</div><div class="line">           <span class="comment">// 传入data就遍历然后拼接给param</span></div><div class="line">           <span class="keyword">if</span> (defaults.data) &#123;</div><div class="line">               <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> defaults.data) &#123;</div><div class="line">                   param += key + <span class="string">'='</span> + defaults.data[key] + <span class="string">'&amp;'</span>;</div><div class="line">               &#125;</div><div class="line">           &#125;;</div><div class="line">           script.src = defaults.url + <span class="string">'?'</span> + param + defaults.jsonp + <span class="string">'='</span> + cbName;</div><div class="line">           <span class="keyword">var</span> head = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'head'</span>)[<span class="number">0</span>];</div><div class="line">           head.appendChild(script);</div><div class="line">       &#125;;</div></pre></td></tr></table></figure>
<h2 id="后台的data-php代码示例-1"><a href="#后台的data-php代码示例-1" class="headerlink" title="后台的data.php代码示例"></a>后台的data.php代码示例</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span> </div><div class="line">  $flag = $_GET[<span class="string">'flag'</span>];</div><div class="line">  $uname = $_GET[<span class="string">'uname'</span>];</div><div class="line">  $cbName = $_GET[<span class="string">'abc'</span>];<span class="comment">// callback名字后台一般是写死的</span></div><div class="line">  <span class="comment">// echo 'var n=123;console.log(n);';</span></div><div class="line">  $arr = <span class="keyword">array</span>(<span class="string">'username'</span>=&gt;<span class="string">'lisi'</span>,<span class="string">'age'</span>=&gt;<span class="string">'12'</span>,<span class="string">'flag'</span>=&gt;$flag,<span class="string">'uname'</span>=&gt;$uname);</div><div class="line">  $str = json_encode($arr);</div><div class="line">  <span class="keyword">echo</span> $cbName.<span class="string">'('</span>.$str.<span class="string">');'</span>;<span class="comment">// 函数调用</span></div><div class="line"> <span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h1 id="执行ajax跨域封装函数"><a href="#执行ajax跨域封装函数" class="headerlink" title="执行ajax跨域封装函数"></a>执行ajax跨域封装函数</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">ajax(&#123;</div><div class="line">    url: <span class="string">'http://doc.studyit.com/data.php'</span>,</div><div class="line">    jsonp: <span class="string">'abc'</span>, <span class="comment">// 该属性的作用就是定制回调函数的key（等号左边的部分）</span></div><div class="line">    jsonpCallback: <span class="string">'hello'</span>, <span class="comment">// 该属性的作用就是定制回调函数的value（等号后面的部分）</span></div><div class="line">    data: &#123;</div><div class="line">        flag: <span class="number">123</span>,</div><div class="line">        uname: <span class="string">'kitty'</span></div><div class="line">    &#125;,</div><div class="line">    dataType: <span class="string">'jsonp'</span>,</div><div class="line">    success: <span class="function"><span class="keyword">function</span>(<span class="params">data</span>) </span>&#123;</div><div class="line">        <span class="built_in">console</span>.log(data); <span class="comment">// &#123;username: "lisi", age: "12", flag: "123", uname: "kitty"&#125;</span></div><div class="line">    &#125;</div><div class="line">&#125;); </div><div class="line"><span class="comment">//http://doc.studyit.com/data.phpdata.php?flag=123&amp;uname=kitty&amp;abc=hello</span></div><div class="line"><span class="comment">//hello(&#123;username: "lisi", age: "12", flag: "123", uname: "kitty"&#125;);</span></div></pre></td></tr></table></figure>
<h1 id="JSONP解决跨域的优缺点"><a href="#JSONP解决跨域的优缺点" class="headerlink" title="JSONP解决跨域的优缺点"></a>JSONP解决跨域的优缺点</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">JSONP的优点是：它不像XMLHttpRequest对象实现的Ajax请求那样受到同源策略的限制；它的兼容性更好，在更加古老的浏览器中都可以运行，不需要XMLHttpRequest或ActiveX的支持；并且在请求完毕后可以通过调用callback的方式回传结果。</div><div class="line">JSONP的缺点则是：它只支持GET请求而不支持POST等其它类型的HTTP请求；它只支持跨域HTTP请求这种情况，不能解决不同域的两个页面之间如何进行JavaScript调用的问题。</div></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/jquery/" rel="tag"># jquery</a>
          
            <a href="/tags/ajax/" rel="tag"># ajax</a>
          
            <a href="/tags/json/" rel="tag"># json</a>
          
            <a href="/tags/jsonp/" rel="tag"># jsonp</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/22/call方法-和-apply方法-以及-bind方法/" rel="next" title="call方法和apply方法以及bind方法">
                <i class="fa fa-chevron-left"></i> call方法和apply方法以及bind方法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/06/07/数组去重/" rel="prev" title="数组去重">
                数组去重 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="http://dynamic-image.yesky.com/300x-/uploadImages/upload/20140912/upload/201409/wylnwjynkxijpg.jpg"
               alt="shine-wl" />
          <p class="site-author-name" itemprop="name">shine-wl</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives/">
            
                <span class="site-state-item-count">21</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#js中ajax的基本步骤"><span class="nav-number">1.</span> <span class="nav-text">js中ajax的基本步骤</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#同源和跨域"><span class="nav-number">2.</span> <span class="nav-text">同源和跨域</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#jQuery中ajax的使用"><span class="nav-number">3.</span> <span class="nav-text">jQuery中ajax的使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#jQuery中ajax同源请求的封装"><span class="nav-number">4.</span> <span class="nav-text">jQuery中ajax同源请求的封装</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ajax中的跨域请求解决方法"><span class="nav-number">5.</span> <span class="nav-text">ajax中的跨域请求解决方法</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#后台的data-php代码示例"><span class="nav-number">5.1.</span> <span class="nav-text">后台的data.php代码示例</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#jQuery中解决跨域的方法"><span class="nav-number">6.</span> <span class="nav-text">jQuery中解决跨域的方法</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#jQuery中ajax的跨域请求封装函数"><span class="nav-number">7.</span> <span class="nav-text">jQuery中ajax的跨域请求封装函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#后台的data-php代码示例-1"><span class="nav-number">7.1.</span> <span class="nav-text">后台的data.php代码示例</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#执行ajax跨域封装函数"><span class="nav-number">8.</span> <span class="nav-text">执行ajax跨域封装函数</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JSONP解决跨域的优缺点"><span class="nav-number">9.</span> <span class="nav-text">JSONP解决跨域的优缺点</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">shine-wl</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动</div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">主题 &mdash; <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.2</div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  





  

  

  

  

  

  

</body>
</html>
